<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品页面</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="../../static/js/Vue-2.6.12.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../static/js/axios.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="/static/js/wangEditor.min.js"></script>

    <style>
        .el-row {
            margin-bottom: 20px;
            &:last-child {
                margin-bottom: 0;
            }
        }
        .el-col {
            border-radius: 4px;
        }

        .grid-content {
            border-radius: 4px;
            min-height: 36px;
        }

        .row-bg {
            padding: 10px 0;
            background-color: #f9fafc;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-drawer {
            overflow: scroll;
        }
    </style>
</head>
<body>
<div id="app">

    <el-row>
        <el-col :span="3">
            <div class="grid-content"></div>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="3">
            <div class="grid-content"></div>
        </el-col>
        <el-col :span="18">
            <el-form label-position="right" label-width="80px" :model="goods">
            <el-tabs v-model="activeName">
                <el-tab-pane label="用户管理" name="first">
                        <el-form-item label ="商品类别">
                            <el-cascader-panel v-model="categorys" :options="categoryList"></el-cascader-panel>
                        </el-form-item>
                        <el-form-item label="名称">
                            <el-input v-model="goods.spu.name"></el-input>
                        </el-form-item>
                        <el-form-item label="副标题">
                            <el-input
                                    type="textarea"
                                    :autosize="{ minRows: 5, maxRows: 10}"
                                    placeholder="请输入内容"
                                    v-model="goods.spu.caption">
                            </el-input>
                        </el-form-item>
                    <el-form-item label="品牌" label-width="80px">
                        <el-select filterable v-model="goods.spu.brandId" placeholder="请选择">
                            <el-option
                                    v-for="brand in brandList"
                                    :key="brand.id"
                                    :label="brand.name"
                                    :value="brand.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-tab-pane>
                <el-tab-pane label="商品详情" name="second">
                    <el-form-item label="商品主图" label-width="80px">
                        <el-upload
                                class="avatar-uploader"
                                action="/file/uploadimg.do?dir=spu"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="图片列表" label-width="80px">
                        <el-upload
                                action="/file/uploadimg.do?dir=spu/spuimages"
                                list-type="picture-card"
                                :file-list="imgList"
                                :limit="5"
                                :on-preview="handlePictureCardPreview"
                                :on-success="updateSpuImages"
                                :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="售后服务">
                        <el-input
                                type="textarea"
                                :autosize="{ minRows: 5, maxRows: 10}"
                                placeholder="请输入内容"
                                v-model="goods.spu.saleService">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="商品介绍">
                        <div id="edit"></div>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="规格" name="third">
                    <el-form-item label="规格启用">
                        <el-switch
                                v-model="goods.spu.isEnableSpec"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                active-value="1"
                                inactive-value="0">
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="规格模板" label-width="80px" v-show="goods.spu.isEnableSpec==1">
                        <el-select v-model="goods.spu.templateId" placeholder="请选择">
                            <el-option
                                    v-for="template in templateList"
                                    :key="template.id"
                                    :label="template.name"
                                    :value="template.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="规格选择" label-width="80px" v-show="goods.spu.isEnableSpec==1">
                        <div v-for="(spec,index) in specItems" :key="index">
                            {{spec.name}}
                            <el-checkbox-group v-model="specs">
                                <el-checkbox @change="addSpecnewSpecItems($event,spec.name,op)" v-for="op in spec.options"
                                             :label="op"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                    {{newSpecItems}}
                    <el-button type="success" @click="saveSpu">保存</el-button>
                </el-tab-pane>
            </el-tabs>
            </el-form>

        </el-col>
        <el-col :span="3">
            <div class="grid-content bg-purple"></div>
        </el-col>
    </el-row>


</div>
</body>

<script type="text/javascript">
    const E = window.wangEditor
    const  editor = new E("#edit")
    new Vue({
        el: "#app",
        data: {
            activeName:"first",
            goods:{spu: {}},
            specs: [],
            categoryList:[],
            categorys:[1,2,3],
            imageUrl:"",
            imgList:[],
            dialogImageUrl:"",
            brandList:[],
            dialogVisible:false,
            specItems: [],
            newSpecItems:null,
            templateList:[]
        },
        created() {
            axios.get(`/category/findcategorymenu.do`).then((res) => {
                this.categoryList = res.data
            })
            axios.get(`/brand/findall.do`).then((res) => {
                this.brandList = res.data
            })
            axios.get(`/template/findall.do`).then((res) => {
                this.templateList = res.data
            })
        },
        mounted(){
            editor.config.uploadImgShowBase64 = true
            editor.create()
        },
        methods: {
            handleAvatarSuccess(res, file) {
                console.log(res,file)
                this.imageUrl = URL.createObjectURL(file.raw);
                this.goods.spu.image = res
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            updateSpuImages(response, file, fileList){
                fileList.forEach((f)=>{
                    f.url = f.response
                })
                this.goods.spu.images = fileList
            },
            findByTemplateId(templateId) {
                // console.log(this.goods.spu.templateId)
                // let templateId = this.goods.spu.templateId;
                axios.get(`/spec/findbytemplateid.do?templateId=${templateId}`).then((res) => {
                    this.specItems = res.data
                    this.specItems.forEach((spec) => {
                        spec.options = spec.options.split(",")
                    })
                })
            },
            addSpecnewSpecItems($event, key, value) {
                // console.log($event)
                // newSpecItems
                // console.log(key,value)
                // 第一次执行该方法
                if (this.newSpecItems == null) {
                    this.newSpecItems = {[key]: [value]}
                    console.log(this.newSpecItems)
                } else {
                    if ($event) {
                        // 单独提一个方法用来寻找key是否存在
                        let isFlag = this.searchKey(this.newSpecItems, key)
                        if (isFlag) { // 如果当前key已存在在newSpecItems里面就push
                            this.newSpecItems[key].push(value)
                        } else {
                            // 不在就新构建一个key-value
                            this.newSpecItems[key] = []
                            this.newSpecItems[key].push(value)
                        }
                    } else {
                        this.newSpecItems[key].splice(this.newSpecItems[key].indexOf(value), 1)
                    }
                }
            },
            searchKey(newSpecItems, key) {
                for (spec in newSpecItems) {
                    if (spec == key) {
                        return true
                    }
                }
                return false;
            },
            saveSpu(){
                this.goods.spu.category1Id = this.categorys[0]
                this.goods.spu.category2Id = this.categorys[1]
                this.goods.spu.category3Id = this.categorys[2]

                this.goods.spu.introduction = editor.txt.html()

                this.goods.spu.specItems = this.newSpecItems
                this.goods.spu.newSpecItems = this.newSpecItems
                let data = this.newSpecItems
                let keys = []
                for (k in data) {
                    // console.log(k)
                    keys.push(k)
                }

                // 最终的数据，{}是为了能够进入数组
                var specList = [{}]
                for (var i = 0; i < keys.length; i++) {
                    var newdata = []
                    // 遍历我们keys，确定最终需要组合数据的次数
                    for (var j = 0; j < data[keys[i]].length; j++) {
                        // 确定当前最终数据中的长度，循环次数
                        for (var n = 0; n < specList.length; n++) {

                            newdata.push({...specList[n], [keys[i]]: data[keys[i]][j]})
                        }
                    }
                    specList = newdata
                }

                console.log(specList)
                this.goods.specList = specList

                axios.post(`/spu/updateSpuSkuList.do`,this.goods).then((res)=>{
                    if(res.data.code==200){
                        this.$message.success(res.data.msg)
                    }else{
                        this.$message.error(res.data.msg)
                    }
                }).catch((err)=>{
                    this.$message.error(err)
                })
            }
        },
        watch: {
            'goods.spu.templateId': {
                handler(newV) {
                    console.log(newV)
                    this.findByTemplateId(newV)
                }
            }
        }
    })
</script>
</html>